package com.syeet.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.syeet.common.constant.AuthServerConstant;
import com.syeet.common.exception.BizCodeEnum;
import com.syeet.common.utils.R;
import com.syeet.common.vo.MemberRespVo;
import com.syeet.gulimall.auth.feign.MemberFeignService;
import com.syeet.gulimall.auth.feign.ThirdPartyFeignSerivce;
import com.syeet.gulimall.auth.vo.UserLoginVo;
import com.syeet.gulimall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author xhl
 * @date 2023/4/13
 */
@Slf4j
@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeignSerivce thirdPartyFeignSerivce;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 访问登录页
     * @return
     */
    @GetMapping(value = "/login.html")
    public String LoginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null){
            //没登录
            return "login";
        }else {
            //返回首页
            return "redirect:http://gulimall.com";
        }

    }

    /**
     * 发送获取验证码
     */
    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        final String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACAH_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            Long time = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - time < 60000) {
                //60s不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        //TODO 1.接口防刷
        //2.验证码再次校验 redis key=phone value=code sms:code: 15216873958->456123
        final String code = RandomStringUtils.randomNumeric(6);
        String finalCode = code + "_" + System.currentTimeMillis();
        //redis缓存验证码，防止同一个phone在60s再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACAH_PREFIX + phone, finalCode, 5, TimeUnit.MINUTES);
        log.info("code值{}:" + code);
        thirdPartyFeignSerivce.sendCode(phone, code);
        return R.ok();
    }

    /**
     * TODO 重定向携带数据，利用session原理，
     * TODO 存在分布式session问题
     * RedirectAttributes attributes模拟重定向携带数据
     *
     * 注册
     * @param vo
     * @param result
     * @param attributes
     * @return
     */
    @PostMapping(value = "/regist")
    public String registRedirect(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            Map<String, String> errorMap = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //model.addAttribute("errors",errorMap);
            attributes.addFlashAttribute("errors", errorMap);
            //若校验用户注册信息是否符合要求,不符合重定向到注册页面重新注册
            //return "forward:/reg.html";
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //检验手机验证码
        String code = vo.getCode();
        final String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACAH_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            //redis存在验证码
            if (code.equals(redisCode.split("_")[0])) {
                //验证通过，先删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACAH_PREFIX + vo.getPhone());
                //调用远程服务真正注册
                R r = memberFeignService.regist(vo);
                if(r.getCode() ==0){
                    //成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    //失败
                    Map<String,String> errorMap = new HashMap<>();
                    errorMap.put("msg",r.getData(new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors", errorMap);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {
                //验证失败
                Map<String, String> map = new HashMap<>();
                map.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", map);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            //redis不存在验证码
            Map<String, String> map = new HashMap<>();
            map.put("code", "验证码错误");
            attributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";

        }

    }

    /**
     * 普通登录
     * @param vo
     * @param redirectAttributes
     * @return
     */
    @PostMapping(value = "/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        R r = memberFeignService.login(vo);
        if(r.getCode() == 0){
            //成功
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);

            return "redirect:http://gulimall.com";
        }else {
            Map<String,String> errorMap = new HashMap<>();
            errorMap.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errorMap);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
